package com.guqj.nio.netty.pstack.server;

import io.netty.channel.ChannelHandlerAppender;
import io.netty.channel.ChannelHandlerContext;

import com.guqj.nio.netty.pstack.pojo.Header;
import com.guqj.nio.netty.pstack.pojo.MessageType;
import com.guqj.nio.netty.pstack.pojo.NettyMessage;

/**
 * 心跳检测-服务端
 * @author guqj
 * @date   2016年11月28日
 */
public class HeartBeatRespHandler extends ChannelHandlerAppender {

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.fireExceptionCaught(cause);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		NettyMessage message = (NettyMessage) msg;
		if (message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_REQ.value()) {
			System.out.println("Receive heart beat message from client: " + message);
			NettyMessage heartBeat = buildHeartBeat();
			System.out.println("Send heart beat response message to client: " + heartBeat);
			ctx.writeAndFlush(heartBeat);
		} else {
			ctx.fireChannelRead(msg);
		}
	}

	private NettyMessage buildHeartBeat() {
		NettyMessage message = new NettyMessage();
		Header header = new Header();
		header.setType(MessageType.HEARTBEAT_RESP.value());
		message.setHeader(header);
		return message;
	}
	
}
